package com.ruoyi.web.service.category.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.SnowFlakeUtils;
import com.ruoyi.web.domain.category.Category;
import com.ruoyi.web.domain.category.MultilevelType;
import com.ruoyi.web.domain.category.Type;
import com.ruoyi.web.mapper.category.CategoryMapper;
import com.ruoyi.web.mapper.category.TypeMapper;
import com.ruoyi.web.service.category.ITypeService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 一级分类tt_typeService业务层处理
 * 
 * @author zq
 * &#064;date  2024-01-09
 */
@Service
public class TypeService implements ITypeService
{

    private final TypeMapper typeMapper;
    private final CategoryMapper categoryMapper;


    public TypeService(TypeMapper typeMapper, CategoryMapper categoryMapper) {
        this.typeMapper = typeMapper;
        this.categoryMapper = categoryMapper;

    }

    /**
     * 查询一级分类tt_type
     * 
     * @param id 一级分类tt_type主键
     * @return 一级分类tt_type
     */
    @Override
    public Type selectTypeById(String id)
    {
        Type type = typeMapper.selectByTypeId(id);
        if(type.getHasLevel()){
            Type type1 = typeMapper.selectTypeById(id, SecurityUtils.getUserId());
            if (Objects.nonNull(type1)){
                return type1;
            }
            return type;

        }else {
            return type;
        }
    }

    /**
     * 查询一级分类tt_type列表
     * 
     * @param type 一级分类tt_type
     * @return 一级分类tt_type
     */
    @Override
    public List<Type> selectTypeList(Type type)
    {
        type.setUserId(SecurityUtils.getUserId());
        List<Type> types = typeMapper.selectTypeList(type);
        String[] typeIds = types.stream().map(Type::getId).toArray(String[]::new);
        Map<String, List<Category>> categoryMap = categoryMapper.selectCategoryPids(typeIds)
                .stream()
                .collect(Collectors.groupingBy(Category::getPid));
        types.forEach(t -> t.setCategoryList(categoryMap.getOrDefault(t.getId(), Collections.emptyList())));
        return types;
    }

    /**
     * 新增一级分类tt_type
     * 
     * @param type 一级分类tt_type
     * @return 结果
     */
    @Transactional
    @Override
    public int insertType(Type type)
    {
        //一级
        checkType(type.getTypeName(),type.getType());

        type.setId(String.valueOf(SnowFlakeUtils.nextId()));
        type.setCreateTime(DateUtils.getNowDate());
        int rows = typeMapper.insertType(type);
        insertCategory(type);
        return rows;
    }

    /**
     * 修改一级分类tt_type
     * 
     * @param type 一级分类tt_type
     * @return 结果
     */
    @Transactional
    @Override
    public int updateType(Type type)
    {
        //校验
        checkType(type.getTypeName(),type.getType());

        return typeMapper.updateType(type);
    }

    /**
     * 批量删除一级分类tt_type
     * 
     * @param ids 需要删除的一级分类tt_type主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTypeByIds(String[] ids)
    {
        typeMapper.deleteCategoryByPids(ids);

        typeMapper.deleteIncomeExpenseByTypeIds(ids,SecurityUtils.getUserId());
        for (String id : ids){
            Type type = typeMapper.selectByTypeId(id);

            if (type.getBuilt() == 0){
                throw new ServiceException("系统内置类型不能删除");
            }
            typeMapper.deleteTypeById(id);
        }
        return 1;
    }

    /**
     * 删除一级分类tt_type信息
     * 
     * @param id 一级分类tt_type主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTypeById(String id)
    {
        typeMapper.deleteCategoryByPid(id);
        return typeMapper.deleteTypeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int multilevelAdd(MultilevelType multilevel) {
        //一级
        checkType(multilevel.getTypeName(),multilevel.getType());

        Type type = new Type();
        type.setTypeName(multilevel.getTypeName());
        type.setType(multilevel.getType());
        type.setBuilt(1);
        type.setRemark(multilevel.getRemark());
        type.setId(String.valueOf(SnowFlakeUtils.nextId()));
        type.setUserId(SecurityUtils.getUserId());

        //二级

        checkCategory(type.getId(),multilevel.getName());
        Category category = new Category();
        category.setName(multilevel.getName());
        category.setIcon(multilevel.getIcon());
        category.setBuilt(1);
        category.setPid(type.getId());

        typeMapper.insertType(type);
        return categoryMapper.insertCategory(category);
    }

    private void checkCategory(String id, String name) {
        Category category = new Category();
        category.setName(name);
        category.setPid(id);
        category.setUserId(SecurityUtils.getUserId());
        List<Category> categories = categoryMapper.selectCategoryList(category);
        if (CollectionUtils.isNotEmpty(categories)){
            throw new ServiceException("重复二级分类名称");
        }
    }

    private void checkType(String typeName, String type) {
        Type type1 = new Type();
        type1.setTypeName(typeName);
        type1.setType(type);
        type1.setUserId(SecurityUtils.getUserId());
        List<Type> types = typeMapper.selectTypeList(type1);
        if (CollectionUtils.isNotEmpty(types)){
            throw new ServiceException("重复一级分类名称");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insideInsert(MultilevelType multilevel) {
        Type type = new Type();
        type.setTypeName(multilevel.getTypeName());
        type.setType(multilevel.getType());
        type.setBuilt(multilevel.getBuilt());
        type.setRemark(multilevel.getRemark());
        type.setId(String.valueOf(SnowFlakeUtils.nextId()));
        type.setUserId(multilevel.getBuilt() == 0 ? null : SecurityUtils.getUserId());

        Category category = new Category();
        category.setName(multilevel.getName());
        category.setIcon(multilevel.getIcon());
        category.setBuilt(multilevel.getBuilt());
        category.setPid(type.getId());

        typeMapper.insertType(type);
        return categoryMapper.insertCategory(category);
    }

    /**
     * 新增分类管理信息
     * 
     * @param type 一级分类tt_type对象
     */
    public void insertCategory(Type type)
    {
        List<Category> categoryList = type.getCategoryList();
        String id = type.getId();
        if (StringUtils.isNotNull(categoryList))
        {
            List<Category> list = new ArrayList<>();
            for (Category category : categoryList)
            {
                //二级
                checkCategory(type.getId(),category.getName());
                category.setId( String.valueOf(SnowFlakeUtils.nextId()));
                category.setCreateTime(DateUtils.getNowDate());
                category.setPid(id);
                list.add(category);
            }
            if (CollectionUtils.isNotEmpty(list))
            {
                typeMapper.batchCategory(list);
            }
        }
    }
}
